/**
 * 时间：2024-08-25
 * 作者：waygc
 * 描述：编辑页主文件，在这个文件中，可以对数据进行编辑操作
 *      因为新增和编辑的页面是一致的，所以新增也通过这个页面实现，只是在提交时，走不同的逻辑
 * 
 */
import React from "react";
import { Form, Input, Select, Upload, InputNumber, Modal } from 'antd';
import { InboxOutlined, PlusOutlined } from '@ant-design/icons'

import { NAME_ENUM_LIST, TARGET_TYPE_ENUM_LIST, FILE_TYPE_ENUM_LIST, PUBLISH_TYPE_ENUM_LIST } from "./../../lib/enums";
import { getBase64, normFile, beforeUpload, stopAutoUpload, checkNumberIsNotEmpty, formatTime } from "./../../lib/utils";
import { base64Upload } from "./../../lib/apis";
import dataApi from "./data";

import "./edit.css";

const { Option } = Select;
const { TextArea } = Input;

const EMPTY_OBJ = {
	name: "",
	nameType: "",
	type: "",
	fileType: "",
	target: "",
	createTime: "",
	classType: "",
	readTime: "",
	picture: "",
	comment: "",
	publish: "",
	files: "",
	fileList: [],
	picList: []
};

class DataTableEdit extends React.Component {
	constructor (props) {
	super(props);
	this.rowId = props.rowId;
	this.getDatas(this.rowId);
	this.formRef = React.createRef(this);
	}

	dataobj = Object.assign({}, EMPTY_OBJ);

	state = {
	modalVisible: false,
	dataobj: Object.assign({}, EMPTY_OBJ)
	};

	rowId = "";

	// 获得数据
	getDatas = async (rowId) => {
		try {
			if (checkNumberIsNotEmpty(rowId)) {
				this.rowId = rowId;
				this.setState({ loading: true });
				const res = await dataApi.getDetail(this.rowId);
				this.dataobj = res.success ? Object.assign({}, res.data) : Object.assign({}, EMPTY_OBJ);

				this.dataobj.picList = [
					{
					urid: Date.now(),
					name: this.dataobj.picture,
					url: this.dataobj.picture,
					stauts: "done"
					}
				];
			} else {
				this.dataobj = Object.assign({}, EMPTY_OBJ);
			}

			const fileList = this.dataobj.files ? this.dataobj.files.split(",") : [];
			this.dataobj.fileList = fileList.map(file => {
				return {
					name: file,
					path: `/upload/${file}`
				}
			});

			if (this.formRef) {
				const { current } = this.formRef;
				if (current) {
					for (const key in this.dataobj) {
					if (key === "key") continue; // 删除界面上没有的内容
					// 这里这么做的原因是在 Form 中，Input 等的 defaultValue 只能在初始化时有效
					current.setFieldValue(key, (this.dataobj[key]).toString());
					}
					this.setState({ dataobj: this.dataobj });
				}
			}
		} catch (err) {
			console.log(err);
		} finally {
		}
	}

	// 监听教程名称
	handleChangeName = (evt) => {
		this.dataobj.name = evt ? evt.target.value : "";
		this.setState({ dataobj: this.dataobj });
	}

	// 监听教程类型
	handleChangeClassType = (evt) => {
		this.dataobj.type = this.dataobj.classType = evt;
		this.setState({ dataobj: this.dataobj });
	}

	// 监听发布类型
	handleChangePublishType = (evt) => {
		this.dataobj.publish = evt;
		this.setState({ dataobj: this.dataobj });
	}

	// 监听教程类型
	handleChangeTgtType = (evt) => {
		this.dataobj.target = evt;
		this.setState({ dataobj: this.dataobj });
	}

	// 监听课件类型
	handleChangeFileType = (evt) => {
		this.dataobj.fileType = evt;
		this.setState({ dataobj: this.dataobj });
	}

	// 监听阅读时间
	handleChangeReadTime = (evt) => {
		this.dataobj.readTime = evt;
		this.setState({ dataobj: this.dataobj });
	}

	// 监听缩略图
	handleChangePicture = async (evt) => {
	const { file } = evt;
	if (file.status === "removed") {
		this.dataobj.picture = "";
		this.dataobj.picList = [];
		this.setState({ dataobj: this.dataobj });
		await dataApi.removeUploadFile(this.rowId, file.name);
	} else {
		if (beforeUpload(file, [ "image/jpeg", "image/png" ], "请选择 JPG 或者 PNG 图片", 2)) {
			getBase64(file, async (result) => {
				const res = await base64Upload(result);
				if (res.success) {
					this.dataobj.picture = `/upload_succeed.jpg`; // 保存获取到的 文件ID + 原始文件名作为保存下来的文件名

					this.dataobj.picList = [
						{
						urid: Date.now(),
						name: this.dataobj.picture,
						url: this.dataobj.picture,
						stauts: "done"
						}
					];

					this.setState({ dataobj: this.dataobj });
					}
				});
			}
		}
	}

	// 监听教程说明
	handleChangeComment = (evt) => {
		this.dataobj.comment = evt.target.id;
	}

	// 监听富文本
	handleRichText = () => {
		// TODO 现在不做处理
	}

	// 监听上传的文件
	handleChangeDocumentFiles = (evt) => {
		if (
			beforeUpload(evt.file,
						[
							"application/vnd.ms-powerpoint",
							"application/vnd.openxmlformats-officedocument.presentationml.presentation"
						],
						"请选择 PPT 或者 PPTX 文件",
						10 )
			) {
			getBase64(evt.file, async (result) => {
				const res = await base64Upload(result);
				if (res.success) {
					this.dataobj.fileList.push(evt.file.name);
					this.setState({ dataobj: this.dataobj });
				}
			});
		} else {
			evt.fileList.pop();
			this.dataobj.fileList = evt.fileList;
			this.setState({ dataobj: this.dataobj });
		}
	}

	// 提交数据
	handleSubmit = () => {
		return new Promise(async (resolve, reject) => {
			try {
				await this.formRef.current.validateFields();

				const submitData = this.state.dataobj;
				submitData.files = submitData.fileList ? submitData.fileList.join() : "";
				delete submitData.fileList;

				if (checkNumberIsNotEmpty(this.rowId)) { // 判断是新建还是编辑
					await dataApi.edit(this.rowId, submitData);
				} else { // 新建
					submitData.count = 0;
					submitData.createTime = formatTime(Date.now());
					await dataApi.save(submitData);
				}
				resolve();
			} catch (err) {
				console.log(err);
				reject({
					valid: true,
					error: err
				});
			}
		});
	}

	handlePreviewPicture = (evt) => {
		this.setState({
			modalVisible: true
		});
	}

	handleModaClose = () => {
		this.setState({
			modalVisible: false
		});
	}

	render () {
	return (
		<div>
			<Form ref={this.formRef}>
				<div>
					<div>
						<Form.Item
							label="教程名称"
							name="name"
							rules={[{ required: true, message: '请输入教程名称' }]}
						>
							<Input allowClear onBlur={this.handleChangeName} />
						</Form.Item>
					</div>
					<div class="datatable-edit-row-item-box">
						<div>
							<Form.Item
								label="教程类型"
								name="classType"
								rules={[{ required: true, message: '请选择一个教程类型' }]}
							>
								<Select onChange={this.handleChangeClassType} allowClear>
									{ NAME_ENUM_LIST.map(obj => (
										<Option key={obj.value}>{obj.label}</Option>
									)) }
								</Select>
							</Form.Item>
						</div>
						<div>
							<Form.Item
								label="发布类型"
								name="publish"
								rules={[{ required: true, message: '请选择一个发布类型' }]}
							>
								<Select onChange={this.handleChangePublishType} allowClear>
									{ PUBLISH_TYPE_ENUM_LIST.map(obj => (
										<Option key={obj.value}>{obj.label}</Option>
									)) }
								</Select>
							</Form.Item>
						</div>
					</div>
					<div class="datatable-edit-row-item-box">
						<div>
							<Form.Item
								label="学习对象"
								name="target"
								rules={[{ required: true, message: '请选择一个学习对象' }]}
							>
								<Select onChange={this.handleChangeTgtType} allowClear>
									{ TARGET_TYPE_ENUM_LIST.map(obj => (
										<Option key={obj.value}>{obj.label}</Option>
									)) }
								</Select>
							</Form.Item>
						</div>
						<div>
							<Form.Item
								label="课件类型"
								name="fileType"
								rules={[{ required: true, message: '请选择一个课件类型' }]}
							>
								<Select onChange={this.handleChangeFileType} allowClear>
									{ FILE_TYPE_ENUM_LIST.map(obj => (
										<Option key={obj.value}>{obj.label}</Option>
									)) }
								</Select>
							</Form.Item>
						</div>
					</div>
					<div class="datatable-edit-row-item-box">
						<div>
							<Form.Item
								label="阅读时间"
								name="readTime"
								rules={[{ required: true, message: '请设置阅读时间' }]}
							>
								<InputNumber min={ 0 } onChange={this.handleChangeReadTime} formatter={value => `${value} 秒`} />
							</Form.Item>
						</div>
						<div>
							<Form.Item
								label="缩略图"
								name="picture"
								rules={[{ required: true, message: '请选择一张缩略图' }]}
							>
								<Upload
									name="picture"
									listType="picture-card"
									class="avatar-uploader"
									fileList={this.state.dataobj.picList}
									action=""
									onPreview={this.handlePreviewPicture}
									beforeUpload={stopAutoUpload} // 不使用框架自带的上传功能
									onChange={this.handleChangePicture}
								>
									{ (() => {
										if (this.state.dataobj.picList.length === 0) {
											return (
												<div>
													<PlusOutlined />
													<div class="ant-upload-text">图片上传</div>
												</div>
											);
										}
									})() }
								</Upload>
							</Form.Item>
						</div>
					</div>
					<div>
						<Form.Item
							label="教程说明"
							name="comment"
							rules={[{ required: true, message: '请输入教程说明' }]}
						>
							<TextArea onBlur={this.handleChangeComment} />
						</Form.Item>
					</div>
					<div>
						{ (() => {
							if (parseInt(this.state.dataobj.fileType || 0) === 1) {
								return (
									<div>
										<Form.Item name="fileList" getValueFromEvent={normFile} noStyle>
											<Upload.Dragger
												name="fileList"
												action=""
												fileList={this.state.dataobj.fileList}
												openFileDialogOnClick={false}
												beforeUpload={stopAutoUpload} // 不使用框架自带的上传功能
												onChange={this.handleChangeDocumentFiles}
											>
												<p class="ant-upload-drag-icon">
													<InboxOutlined />
												</p>
												<p class="ant-upload-text">点击或拖拽文件上传</p>
												<p class="ant-upload-hint">支持文件格式：.ppt 、.pptx 单个文件不能超过 10M</p>
											</Upload.Dragger>
										</Form.Item>
									</div>
								);
							} else {
								return (
									<div>富文本</div>
								);
							}
						})() }
					</div>
				</div>
			</Form>
			<Modal
				open={this.state.modalVisible}
				header=""
				footer=""
				onOk={this.handleModaClose}
				onCancel={this.handleModaClose}
			>
				<img src={this.state.dataobj.picture} alt="" style={{width: "470px", height:"500px"}} />
			</Modal>
		</div>
	);
	};
}

export default DataTableEdit;
